package edu.zju.gis.dbfg.fileserver.model.typeHandler;

import edu.zju.gis.dbfg.common.util.StringUtils;
import edu.zju.gis.dbfg.fileserver.model.ConstructedDataField;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.json.JSONArray;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@MappedTypes(value = {java.util.List.class})
@MappedJdbcTypes(value = {JdbcType.VARCHAR})
public class FieldsTypeHandler extends BaseTypeHandler<List<ConstructedDataField>> {
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, List<ConstructedDataField> parameter, JdbcType jdbcType) throws SQLException {
        ps.setString(i, parameter.toString());
    }

    @Override
    public List<ConstructedDataField> getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String str = rs.getString(columnName);
        if (StringUtils.isBlank(str)) return null;
        JSONArray array = new JSONArray(str);
        List<ConstructedDataField> result = new ArrayList<>();
        for (Object o : array) {
            result.add(new ConstructedDataField());
        }
        return result;
    }

    @Override
    public List<ConstructedDataField> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String str = rs.getString(columnIndex);
        JSONArray array = new JSONArray(str);
        List<ConstructedDataField> result = new ArrayList<>();
        for (Object o : array) {
            result.add(new ConstructedDataField());
        }
        return result;
    }

    @Override
    public List<ConstructedDataField> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String str = cs.getString(columnIndex);
        if (StringUtils.isBlank(str)) return null;
        JSONArray array = new JSONArray(str);
        List<ConstructedDataField> result = new ArrayList<>();
        for (Object o : array) {
            result.add(new ConstructedDataField());
        }
        return result;
    }
}
